package com.kcht.sylyg08.service;

import com.kcht.adp.common.event.ADPEventPublisher;
import com.kcht.adp.common.event.EventLevel;
import com.kcht.adp.common.log.Logger;
import com.kcht.adp.pagination.Page;
import com.kcht.sylyg08.ctrl.vo.TaskVO;
import com.kcht.sylyg08.dao.*;
import com.kcht.sylyg08.service.model.ContainerActionDetails;
import com.kcth.sylyg08.entity.Container;
import com.kcth.sylyg08.entity.ContainerStatus;
import com.kcth.sylyg08.entity.Task;
import com.kcth.sylyg08.entity.TaskStatus;

import javax.ejb.EJB;
import javax.enterprise.context.RequestScoped;
import javax.inject.Inject;
import javax.transaction.Transactional;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * 任务业务类，封装了部分任务表示层操作相关方法
 */
@RequestScoped
@Transactional()
public class TaskService {
    @Inject
    private Logger logger;
    @EJB
    private ITaskDao dao;
    @EJB
    private IContainerDao cDao;
    @EJB
    private IMaterialContainerBoundDao mcbDao;
    @EJB
    private IOutGoingPoolDao ogpDao;
    //    @EJB
//    private IContainerStatusTransformRecordDao cstrDao;
//    @EJB
//    private IInterveneRecordDao irDao;
    @EJB
    private ICurrentContainerStatusDao ccsDao;

    @Inject
    private IContainerStatusService containerStatusService;

    /**
     * 保存任务
     *
     * @param task 任务对象
     */
    public void save(Task task) {
        if (task.getId() == null) {
            dao.save(task);
        } else {
            dao.merge(task);
        }
    }

    /**
     * 分页查询任务列表
     *
     * @param page 包括查询参数，分页信息
     * @return 查询结果列表
     */
    public Page<Task, TaskVO> list(Page<Task, TaskVO> page) {
        if ("0".equals(page.getParameter().getStatus())) {
            page.getParameter().setStatus(null);
        }
        return dao.getPageListByJPQL("Task.queryTaskList", page);
    }

    /**
     * 分页查询异常任务列表
     *
     * @param page 包括查询参数，分页信息
     * @return 查询结果列表
     */
    public Page<Task, TaskVO> listErrorTask(Page<Task, TaskVO> page) {
        return dao.getPageListByJPQL("Task.queryErrorTaskList", page);
    }

    /**
     * 确认异常任务，将异常任务标记为已完成，并且修改相关料框状态
     * （该功能暂未完成）
     *
     * @param id      任务编号
     * @param name    用户名
     * @param details 详情
     */
    public String confirmErrorTask(Long id, String name, String details, String containers) {
        String msg = null;
        Task task = dao.get(id);
//        task.setStatus(TaskStatus.完成);
        ContainerStatus status = null;
        ContainerActionDetails action = new ContainerActionDetails();
        action.setRtnCode(2);       //rtnCode =2 表示 此料框为人为修改料框状态而导致的料框状态改变
/*        switch (task.getTaskType()) {
            case PRODUCT_OK:
                status = ContainerStatus.在库;
                break;
            case REPAIR:
                status = ContainerStatus.已出库;
                break;
            case OUT_GOING:
                status = ContainerStatus.已出库;
                break;
            case RETREAT:
                status = ContainerStatus.在库;
        }*/
        if (Objects.nonNull(task.getContainerId())) {
            containerStatusService.changeContainerStatusByIntervene(task.getContainerId(), status, name, details);
            action.setContainerId(task.getContainerId());
            action.setMaterialType(task.getMaterialType());
            action.setTaskType(task.getTaskType());
            ADPEventPublisher.publishEvent(action, EventLevel.Negligible);
            msg = "任务状态已修改为已完成";
        } else {
            String[] containerIds = containers.split(" ");
            if (containerIds.length == 0 && "" != containers) {
                containerIds = new String[]{containers};
            }
            List<ContainerActionDetails> actions = new ArrayList<ContainerActionDetails>();
//            boolean flag = true;
            for (String containerId : containerIds) {
                Container container = cDao.get(containerId);
                if (Objects.isNull(container)) {
                    return containerId + "料框不存在！";
                    /*flag = false;
                    break;*/
                } else if (!container.getContainerType().equals(task.getMaterialType())) {
                    return containerId + "料框所装物料和任务要求不匹配";
                    /*flag = false;
                    break;*/
                } /*else if (!ContainerStatus.在库.equals(ccsDao.getByContainerId(containerId).getStatus())) {
                    return containerId + "料框状态不为在库！";*/
                    /*flag = false;
                    break;*/
                /*} else {
                    containerStatusService.changeContainerStatusByIntervene(containerId, status, name, details);
                    action.setContainerId(containerId);
                    ADPEventPublisher.publishEvent(action);
                    msg = "任务状态已修改为已完成";
                }*/
            }
            if (countMaterialCount(id, containerIds)) {
                for (String containerId : containerIds) {
                    containerStatusService.changeContainerStatusByIntervene(containerId, status, name, details);
                    action.setContainerId(containerId);
                    ADPEventPublisher.publishEvent(action, EventLevel.Negligible);
                    msg = "任务状态已修改为已完成";
                }
            } else {
                return "物料数量不匹配";
            }
        }
        if (!"物料数量不匹配".equals(msg)) {
            task.setStatus(TaskStatus.完成);
            dao.merge(task);
        }
        return msg;
        /*ContainerStatusTransformRecord cstrecord = new ContainerStatusTransformRecord();
        cstrecord.setTransformDate(new Date());
        cstrecord.setContainerId(task.getContainerId());
        cstrecord.setIsAbnormal(true);
        cstrDao.save(cstrecord);
        CurrentContainerStatus ccStatus = ccsDao.getByContainerId(task.getContainerId());
        switch (task.getTaskType()) {
            case PRODUCT_OK:
                ccStatus.setStatus(ContainerStatus.在库);
                break;
            case REPAIR:
                ccStatus.setStatus(ContainerStatus.已出库);
                break;
            case OUT_GOING:
                ccStatus.setStatus(ContainerStatus.已出库);
                break;
            case RETREAT:
                ccStatus.setStatus(ContainerStatus.在库);
        }
        ccStatus.setToBeMoven(false);
        ccStatus.setChangeTime(new Date());
        ccsDao.merge(ccStatus);
        InterveneRecord iRecord = new InterveneRecord();
        iRecord.setContainerStatusTransformRecordId(cstrecord.getId());
        iRecord.setIntervener(name);
        iRecord.setDetails(details);
        iRecord.setContainerStatus(ccStatus.getStatus());
        irDao.save(iRecord);*/
    }

    private boolean countMaterialCount(long taskId, String[] containerIds) {
        int count = 0;
        for (String containerId : containerIds) {
            count += mcbDao.getByContainerId(containerId).getCount();
        }
        return dao.get(taskId).getCount() == count;
    }

}
